import json
import os

class Config:
    def __init__(self, config_file="config.json"):
        self.config_file = config_file
        self.config = self.load_config()

    def load_config(self):
        """加载配置文件"""
        default_config = {
            "organization": "DefaultOrg",
            "collection_interval": 30,  # 采集间隔（秒）
            "log_directory": "./logs",
        }

        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                # 合并默认配置
                default_config.update(config)
                return default_config
            except Exception as e:
                print(f"配置文件读取失败: {e}, 使用默认配置")
                return default_config
        else:
            # 创建默认配置文件
            self.save_config(default_config)
            return default_config

    def save_config(self, config=None):
        """保存配置文件"""
        if config is None:
            config = self.config

        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)

    def get(self, key, default=None):
        """获取配置项"""
        return self.config.get(key, default)
if __name__ == "__main__":
    c = Config()
    c.load_config()
    print(c.get("kafka_host"))
